package respositories

import (
	"chat/models"
	"chat/pkg/util"
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

func getGroupColl() (*mongo.Collection, error) {
	return util.Mongo.GetChatCollection("Group")
}

func FindGroup(group *models.Group) ([]models.Group, error) {
	c, err := getGroupColl()
	if err != nil {
		return nil, err
	}
	c2, err := c.Find(context.Background(), group.ToBson())
	if err != nil {
		return nil, err
	}
	var groups []models.Group
	err = c2.All(context.TODO(), &groups)
	if err != nil {
		return nil, err
	}
	return groups, nil
}

func InsertGroup(group *models.Group) error {
	c, err := getGroupColl()
	if err != nil {
		return err
	}
	ior, err := c.InsertOne(context.Background(), group.ToBson())
	if err != nil {
		return err
	}
	group.Id = ior.InsertedID.(primitive.ObjectID)
	return nil
}

func DeleteGroupById(group *models.Group) error {
	c, err := getGroupColl()
	if err != nil {
		return err
	}

	dr, err := c.DeleteOne(context.TODO(), group.ToBson())
	if err != nil {
		return err
	}
	if dr.DeletedCount != 1 {
		return errors.New("delete failed")
	}
	return nil
}
